<template>
  <view class="groupMembers">
    <topTitle :title="'群成员（' + groupInfo.member?.length + '）'" />
    <view class="com">
      <search @update:searchValue="searchFn" />
      <view class="list">
        <view>群主</view>
        <view>
          <view @tap="searchAddFn(groupInfo.member[0])">
            <up-avatar
              class="avatar"
              mode="aspectFill"
              :src="groupInfo.member[0]?.picture"
              size="50"
            ></up-avatar>
            {{ groupInfo.member[0]?.nick_name }}
          </view>
        </view>
      </view>
      <view class="list">
        <view>群成员</view>
        <view>
          <view
            v-for="(item, idx) in groupInfo.member"
            :key="idx"
            v-show="filteredMembers(item, idx)"
            @tap="searchAddFn(item)"
          >
            <up-avatar
              class="avatar"
              mode="aspectFill"
              :src="item.picture"
              size="50"
            ></up-avatar>
            {{ item.notes || item.nick_name }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import { GroupInfo, FriendInfoSelect } from "@/api/ImApi";

const instance = getCurrentInstance()?.appContext.config.globalProperties;
let groupInfo = ref<any>({
  member: [],
});
let myUserInfo = ref<any>({});

// 群详情
const getGroupDetails = async (chatId: string) => {
  myUserInfo.value = uni.getStorageSync("userInfo");
  const messages = await instance?.$db.loadData("chatList", { chatId });
  groupInfo.value = messages[0];

  GroupInfo({ group_id: chatId }).then((e) => {
    groupInfo.value = {
      ...groupInfo.value,
      ...e,
    };
  });
};
let searchValue = ref<string>("");
// 搜索功能
const searchFn = (e: string) => {
  searchValue.value = e.trim();
};
// 过滤
const filteredMembers = (item: any, idx: number) => {
  return (
    idx != 0 &&
    (searchValue
      ? item.nick_name.toLowerCase().indexOf(searchValue.value.toLowerCase()) !=
        -1
      : true)
  );
};
// 前往好友详情
const searchAddFn = async (item: any) => {
  if (myUserInfo.value.user_id == item.user_id) {
    return;
  }

  let res = await FriendInfoSelect({ user_id: item.user_id, loading: 1 });

  let friendList = await instance?.$db.loadData("friendList", {
    user_id: item.user_id,
  });
  if (friendList.length) {
    instance?.goTo("/pages/chat/friendDetails?chatId=" + item.user_id);
  } else {
    instance?.goTo(
      "/pages/create/searchAdd?searchValue=" +
        encodeURIComponent(JSON.stringify({ ...item, ...res, type: 0 }))
    );
  }
};
onLoad((options) => {
  getGroupDetails(options?.chatId);
});
onReachBottom(() => {
  console.log("123");
});
</script>
<style scoped lang="scss">
@import "../../static/scss/group.scss";
</style>
